package com.joolun.web.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.joolun.activity.domain.ActivityAward;
import com.joolun.activity.domain.ActivityAwardInfo;
import com.joolun.activity.domain.ActivityInfo;
import com.joolun.activity.domain.ActivityTake;
import com.joolun.activity.domain.ActivityTakeInfo;
import com.joolun.activity.domain.ShareInfo;
import com.joolun.activity.domain.VoteInfo;
import com.joolun.activity.service.IActivityAwardInfoService;
import com.joolun.activity.service.IActivityAwardService;
import com.joolun.activity.service.IActivityInfoService;
import com.joolun.activity.service.IActivityTakeInfoService;
import com.joolun.activity.service.IActivityTakeService;
import com.joolun.activity.service.IShareInfoService;
import com.joolun.activity.service.IVoteInfoService;
import com.joolun.activity.vo.ActivityInfoVo;
import com.joolun.activity.vo.ActivityTakeInfoUserVo;
import com.joolun.activity.vo.ActivityTakeVo;
import com.joolun.activity.vo.OpenIdVo;
import com.joolun.activity.vo.ShareInfoVo;
import com.joolun.activity.vo.ShareInfoVoList;
import com.joolun.activity.vo.ShareUrlVo;
import com.joolun.activity.vo.SupportShareInfoVo;
import com.joolun.common.annotation.Log;
import com.joolun.common.config.JooLunConfig;
import com.joolun.common.constant.Constants;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.core.domain.entity.SysDictData;
import com.joolun.common.core.domain.entity.SysUser;
import com.joolun.common.core.domain.model.LoginBody;
import com.joolun.common.core.domain.model.LoginUser;
import com.joolun.common.core.page.TableDataInfo;
import com.joolun.common.enums.BusinessType;
import com.joolun.common.utils.DateUtils;
import com.joolun.common.utils.SecurityUtils;
import com.joolun.common.utils.ServletUtils;
import com.joolun.common.utils.StringUtils;
import com.joolun.common.utils.file.FileUploadUtils;
import com.joolun.framework.web.domain.server.Sys;
import com.joolun.framework.web.service.SysLoginService;
import com.joolun.framework.web.service.SysPermissionService;
import com.joolun.framework.web.service.TokenService;
import com.joolun.system.service.ISysDictDataService;
import com.joolun.weixin.entity.WxUser;
import com.joolun.weixin.service.WxUserService;
import com.joolun.activity.vo.ActivityAwardVo;
import com.joolun.activity.vo.ActivityTakeInfoVo;
import com.joolun.weixin.vo.AuthorizationUrl;
import com.joolun.activity.vo.DrawAwardVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/app")
@Api(value = "app", tags = "移动端")
public class AppApi extends BaseController {
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IActivityInfoService activityInfoService;
    @Autowired
    private IActivityAwardService activityAwardService;
    @Autowired
    private IActivityTakeService activityTakeService;
    @Autowired
    private IActivityTakeInfoService activityTakeInfoService;
    @Autowired
    private IActivityAwardInfoService activityAwardInfoService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Autowired
    private WxMpService wxService;

    @Autowired
    private IShareInfoService iShareInfoService;
    @Autowired
    private IVoteInfoService iVoteInfoService;

    @Value("${wx.url}")
    private String url;
    @Value("${wx.templateId}")
    private String templateId;

    @ApiOperation(value ="大堂经理/开奖人员登录")
    @PostMapping("/login/app")
    public AjaxResult loginApp(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginApp(loginBody.getUsername(), loginBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation(value ="大堂经理/开奖人员授权信息获取")
    @GetMapping("/getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @ApiOperation(value ="大堂经理/开奖人员获取活动信息")
    @GetMapping("/list/activityinfo")
    public AjaxResult listActivityInfo()
    {
        List<ActivityInfo> list = activityInfoService.list(new QueryWrapper<ActivityInfo>()
        .select("activity_code","name").ne("status","3").orderByDesc("open_time"));
        return AjaxResult.success(list);
    }

    @ApiOperation(value ="开奖人员获取活动奖品信息")
    @PostMapping("/list/activityaward")
    public AjaxResult listActivityAward(@RequestBody ActivityAwardVo activityAwardVo)
    {
        List<ActivityAward> list = activityAwardService.list(new QueryWrapper<ActivityAward>()
                .select("award_code","level","name","award_num")
                .eq("activity_code",activityAwardVo.getActivityCode())
                .eq("del_flag","0")
                .orderByAsc("level"));
        list.stream().forEach(aa->{
            SysDictData dict = iSysDictDataService.getOne(new QueryWrapper<SysDictData>()
                    .eq("dict_type","activity_award_level").eq("dict_value",aa.getLevel()));
            aa.setLevelName(dict.getDictLabel());
        });
        return AjaxResult.success(list);
    }

    @ApiOperation(value ="开奖人员活动开奖")
    @Log(title = "开奖人员活动开奖", businessType = BusinessType.UPDATE)
    @PutMapping("/draw/award")
    public AjaxResult drawAward(@RequestBody DrawAwardVo drawAwardVo)
    {
        activityAwardService.drawAward(drawAwardVo);
        return AjaxResult.success();
    }

    @ApiOperation(value ="获取当前开奖参与人员默认20个")
    @PutMapping("/draw/award/get/take")
    public AjaxResult drawAwardGetTake(@RequestBody DrawAwardVo drawAwardVo)
    {
        return AjaxResult.success(activityAwardService.drawAwardGetTake(drawAwardVo));
    }

    @ApiOperation(value ="开奖人员获取活动中奖信息（最新的10条）")
    @PostMapping("/list/activityawardinfo")
    public AjaxResult listActivityAwardInfo(@RequestBody ActivityAwardVo activityAwardVo)
    {

        List<ActivityAwardInfo> list = activityAwardInfoService.list(new QueryWrapper<ActivityAwardInfo>()
                .select("take_time","activity_take_code","award_code","user_name","phone")
                .eq("activity_code",activityAwardVo.getActivityCode())
                .eq("status","2")
                .ge("take_time",DateUtils.getDate()+" 00:00:00")
                .le("take_time",DateUtils.getDate()+" 23:59:59")
                .orderByDesc("take_time")
                .last("limit 0,10"));
        list.stream().forEach(aa->{
            ActivityAward activityAward= activityAwardService.getOne(new QueryWrapper<ActivityAward>()
                    .eq("award_code",aa.getAwardCode()));
            SysDictData dict = iSysDictDataService.getOne(new QueryWrapper<SysDictData>()
                    .eq("dict_type","activity_award_level").eq("dict_value",activityAward.getLevel()));
            aa.setLevelName(dict.getDictLabel());
            aa.setName(activityAward.getName());
        });
        return AjaxResult.success(list);
    }

    @ApiOperation(value ="开奖人员获取奖品中奖信息")
    @PostMapping("/list/activityawardinfo/award")
    public AjaxResult listActivityAwardInfoAward(@RequestBody DrawAwardVo drawAwardVo)
    {
        List<ActivityAwardInfo> list = activityAwardInfoService.list(new QueryWrapper<ActivityAwardInfo>()
                .select("take_time","activity_take_code","award_code","user_name","phone")
                .eq("award_code",drawAwardVo.getAwardCode())
                .eq("status","2")
                .orderByDesc("take_time"));
        list.stream().forEach(aa->{
            ActivityAward activityAward= activityAwardService.getOne(new QueryWrapper<ActivityAward>()
                    .eq("award_code",aa.getAwardCode()));
            SysDictData dict = iSysDictDataService.getOne(new QueryWrapper<SysDictData>()
                    .eq("dict_type","activity_award_level").eq("dict_value",activityAward.getLevel()));
            aa.setLevelName(dict.getDictLabel());
            aa.setName(activityAward.getName());
        });
        return AjaxResult.success(list);
    }

    @ApiOperation(value ="大堂经理生成活动参与码")
    @Log(title = "大堂经理生成活动参与码", businessType = BusinessType.INSERT)
    @PostMapping("/create/activitytake")
    public AjaxResult createActivityTake(@RequestBody ActivityTakeVo activityTake)
    {
        return AjaxResult.success(activityTakeService.insertActivityTakeVo(activityTake));
    }

    @ApiOperation(value ="大堂经理生成活动参与链接")
    @Log(title = "大堂经理生成活动参与链接", businessType = BusinessType.INSERT)
    @PostMapping("/create/authorizationurl")
    public AjaxResult createAuthorizationUrl(@RequestBody AuthorizationUrl authorizationUrl)
    {
        return AjaxResult.success(wxUserService.createAuthorizationUrl(authorizationUrl));
    }

    @ApiOperation(value ="大堂经理进行核销")
    @GetMapping(value = "/check/{activityTakeCode}")
    public AjaxResult checkInfo(@PathVariable("activityTakeCode") String activityTakeCode)
    {
        ActivityAwardInfo activityAwardInfo= activityAwardInfoService.getOne(new QueryWrapper<ActivityAwardInfo>()
        .eq("award_info_code",activityTakeCode));
        if(null==activityAwardInfo){
            return AjaxResult.error("信息不存在");
        }
        if(activityAwardInfo.getStatus().equals("1")){
            return AjaxResult.error("未中奖不能核销");
        }
        if(activityAwardInfo.getStatus().equals("3")){
            return AjaxResult.error("请勿重复核销");
        }
        SysUser sysUser= SecurityUtils.getLoginUser().getUser();
        activityAwardInfo.setUserId(sysUser.getUserId());
        activityAwardInfo.setCheckUser(sysUser.getUserName());
        activityAwardInfo.setDeptId(sysUser.getDept().getDeptId());
        activityAwardInfo.setDeptName(sysUser.getDept().getDeptName());
        activityAwardInfo.setCheckTime(DateUtils.getNowDate());
        activityAwardInfo.setStatus("3");
        return AjaxResult.success(activityAwardInfoService.updateById(activityAwardInfo));
    }

    @ApiOperation(value ="大堂经理帮助用户绑定活动参与码")
    @PostMapping("/binding/activittakeinfo/for/user")
    public AjaxResult bindingActivityTakeInfoForUser(@RequestBody ActivityTakeInfoVo activityTakeInfoVo)
    {
        Integer integer=activityTakeInfoService.count(new QueryWrapper<ActivityTakeInfo>()
                .eq("status","1")
                .eq("take_code",activityTakeInfoVo.getTakeCode()));
        if(integer<=0){
            return AjaxResult.error("请勿重复绑定");
        }
        //根据手机号查询用户
        WxUser wxUser= wxUserService.getOne(new QueryWrapper<WxUser>().eq("phone",activityTakeInfoVo.getPhone()));
        if(null==wxUser){
            wxUser=new WxUser();
            wxUser.setName(activityTakeInfoVo.getName());
            wxUser.setPhone(activityTakeInfoVo.getPhone());
            wxUserService.save(wxUser);
        }
        //绑定用户与参与码信息
        activityTakeInfoService.update(new UpdateWrapper<ActivityTakeInfo>()
                .set("status","2")
                .set("binding_time",DateUtils.dateTimeNow())
                .set("name",activityTakeInfoVo.getName())
                .set("phone",wxUser.getPhone())
                .eq("take_code",activityTakeInfoVo.getTakeCode())
        );
        return AjaxResult.success();
    }


    @ApiOperation(value ="用户授权绑定活动参与码---绑定页面固定")
    @Log(title = "用户授权绑定活动参与码", businessType = BusinessType.UPDATE)
    @PostMapping("/binding/activittakeinfo")
    public AjaxResult bindingActivityTakeInfo(@RequestBody ActivityTakeInfoVo activityTakeInfoVo)
    {
        Integer integer=activityTakeInfoService.count(new QueryWrapper<ActivityTakeInfo>()
                .eq("status","1")
                .eq("take_code",activityTakeInfoVo.getTakeCode()));
        if(integer<=0){
            return AjaxResult.error("请勿重复绑定");
        }
        WxOAuth2AccessToken wxOAuth2AccessToken= wxUserService.bindingActivityTakeInfo(activityTakeInfoVo.getCode());
        if(null==wxOAuth2AccessToken){
            return AjaxResult.error("微信授权失败",activityTakeInfoVo);
        }
        WxUser wxUser= wxUserService.getOne(new QueryWrapper<WxUser>().eq("open_id",wxOAuth2AccessToken.getOpenId()));
        if(null==wxUser){
            wxUser=new WxUser();
            wxUser.setOpenId(wxOAuth2AccessToken.getOpenId());
            wxUser.setName(activityTakeInfoVo.getName());
            wxUser.setPhone(activityTakeInfoVo.getPhone());
            wxUserService.save(wxUser);
        }
        //绑定用户与参与码信息
        activityTakeInfoService.update(new UpdateWrapper<ActivityTakeInfo>()
                .set("status","2")
                .set("open_id",wxUser.getOpenId())
                .set("binding_time",DateUtils.dateTimeNow())
                .set("name",activityTakeInfoVo.getName())
                .set("phone",wxUser.getPhone())
                .eq("take_code",activityTakeInfoVo.getTakeCode())
                );
        return AjaxResult.success();
    }

    @ApiOperation(value ="用户授权查询活动参与中奖信息")
    @PostMapping("/binding/activittakeinfo/user")
    public AjaxResult bindingActivityTakeInfoUser(@RequestBody ActivityTakeInfoUserVo activityTakeInfoVo)
    {
        WxOAuth2AccessToken wxOAuth2AccessToken= wxUserService.bindingActivityTakeInfo(activityTakeInfoVo.getCode());
        if(null==wxOAuth2AccessToken){
            return AjaxResult.error("绑定失败",activityTakeInfoVo);
        }
        //查询参与信息
       List<ActivityTakeInfo>  activityTakeInfos=activityTakeInfoService.list(new QueryWrapper<ActivityTakeInfo>()
                .select("activity_code","take_code","activity_take_code","status","binding_time")
                .eq("open_id",wxOAuth2AccessToken.getOpenId()).orderByDesc("binding_time"));
        //查询中奖信息
        List<ActivityAwardInfo> activityAwardInfos=activityAwardInfoService.list(new QueryWrapper<ActivityAwardInfo>()
                .select("activity_code","award_code","award_info_code","status","take_time")
                .eq("open_id",wxOAuth2AccessToken.getOpenId()).orderByDesc("take_time"));
        activityAwardInfos.stream().forEach(aa->{
            ActivityAward activityAward= activityAwardService.getOne(new QueryWrapper<ActivityAward>()
                    .eq("award_code",aa.getAwardCode()));
            SysDictData dict = iSysDictDataService.getOne(new QueryWrapper<SysDictData>()
                    .eq("dict_type","activity_award_level").eq("dict_value",activityAward.getLevel()));
            aa.setLevelName(dict.getDictLabel());
            aa.setName(activityAward.getName());
        });
        AjaxResult ajax = AjaxResult.success();
        ajax.put("activityTakeInfos", activityTakeInfos);
        ajax.put("activityAwardInfos", activityAwardInfos);
        return ajax;
    }

    @ApiOperation(value ="用户授权查询活动参与中奖信息通过手机号查询")
    @PostMapping("/binding/activittakeinfo/user/phone")
    public AjaxResult bindingActivityTakeInfoUserPhone(@RequestBody ActivityTakeInfoUserVo activityTakeInfoVo)
    {
        //查询参与信息
        List<ActivityTakeInfo>  activityTakeInfos=activityTakeInfoService.list(new QueryWrapper<ActivityTakeInfo>()
                .select("activity_code","take_code","activity_take_code","status","binding_time")
                .eq("phone",activityTakeInfoVo.getPhone())
                .eq("name",activityTakeInfoVo.getName())
                .orderByDesc("binding_time"));
        //查询中奖信息
        List<ActivityAwardInfo> activityAwardInfos=activityAwardInfoService.list(new QueryWrapper<ActivityAwardInfo>()
                .select("activity_code","award_code","award_info_code","status","take_time")
                .eq("phone",activityTakeInfoVo.getPhone())
                .eq("user_name",activityTakeInfoVo.getName())
                .orderByDesc("take_time"));
        activityAwardInfos.stream().forEach(aa->{
            ActivityAward activityAward= activityAwardService.getOne(new QueryWrapper<ActivityAward>()
                    .eq("award_code",aa.getAwardCode()));
            SysDictData dict = iSysDictDataService.getOne(new QueryWrapper<SysDictData>()
                    .eq("dict_type","activity_award_level").eq("dict_value",activityAward.getLevel()));
            aa.setLevelName(dict.getDictLabel());
            aa.setName(activityAward.getName());
        });
        AjaxResult ajax = AjaxResult.success();
        ajax.put("activityTakeInfos", activityTakeInfos);
        ajax.put("activityAwardInfos", activityAwardInfos);
        return ajax;
    }

    /**
     * 发送中奖通知
     */
    @ApiOperation(value = "发送中奖通知")
    @GetMapping("/send/wxmsg/template/{id}")
    public AjaxResult sendWxMpTemplate(@PathVariable("id") String id){
        //查询中奖信息
        ActivityAwardInfo activityAwardInfo= activityAwardInfoService.getById(id);
        if(activityAwardInfo.getStatus().equals("1")){
        	return AjaxResult.error("此信息未中奖");
        }
        if(StringUtils.isEmpty(activityAwardInfo.getOpenId())){
            return AjaxResult.error("当前用户未使用微信授权,此功能不能使用");
        }
        //发送微信中奖消息
        WxMpTemplateMessage wxMpTemplateMessage=new WxMpTemplateMessage();
        WxMpTemplateMsgService wxMpTemplateMsgService = wxService.getTemplateMsgService();
        wxMpTemplateMessage.setToUser(activityAwardInfo.getOpenId());
        wxMpTemplateMessage.setTemplateId(templateId);
        wxMpTemplateMessage.setUrl(url);
        List<WxMpTemplateData> wxMpTemplateDatas=new ArrayList<>();
        WxMpTemplateData wxMpTemplateDataOne=new WxMpTemplateData();
        wxMpTemplateDataOne.setName("first");
        wxMpTemplateDataOne.setValue("幸运大抽奖");
        wxMpTemplateDataOne.setColor("#E33F32");
        wxMpTemplateDatas.add(wxMpTemplateDataOne);
        WxMpTemplateData wxMpTemplateDataTwo=new WxMpTemplateData();
        wxMpTemplateDataTwo.setName("keyword1");
        wxMpTemplateDataTwo.setValue("尊敬的用户");
        wxMpTemplateDataTwo.setColor("#00000");
        wxMpTemplateDatas.add(wxMpTemplateDataTwo);
        WxMpTemplateData wxMpTemplateDataThree=new WxMpTemplateData();
        wxMpTemplateDataThree.setName("keyword2");
        wxMpTemplateDataThree.setValue(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,activityAwardInfo.getTakeTime()));
        wxMpTemplateDataThree.setColor("#E33F32");
        wxMpTemplateDatas.add(wxMpTemplateDataThree);
        WxMpTemplateData wxMpTemplateDataFour=new WxMpTemplateData();
        wxMpTemplateDataFour.setName("keyword3");
        wxMpTemplateDataFour.setValue("点击详情查看获奖信息");
        wxMpTemplateDataFour.setColor("#E33F32");
        wxMpTemplateDatas.add(wxMpTemplateDataFour);
        WxMpTemplateData wxMpTemplateDataFive=new WxMpTemplateData();
        wxMpTemplateDataFive.setName("remark");
        wxMpTemplateDataFive.setValue("前往参与网点进行奖品领取");
        wxMpTemplateDataFive.setColor("#E33F32");
        wxMpTemplateDatas.add(wxMpTemplateDataFive);
        wxMpTemplateMessage.setData(wxMpTemplateDatas);
        try {
        	wxMpTemplateMsgService.sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
        	e.printStackTrace();
        	log.error("微信中奖消息发送失败{}{}{}", e,activityAwardInfo.getOpenId(),templateId);
        	return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("发送成功");
    }

    @ApiOperation(value ="获取授权链接")
    @PostMapping("/wx/code")
    public AjaxResult wxCode(@RequestBody AuthorizationUrl authorizationUrl)
    {
        return AjaxResult.success(wxUserService.createAuthorizationUrl(authorizationUrl));
    }


    @ApiOperation(value ="活动访问量增加")
    @PostMapping("/add/activityInfo/num")
    public AjaxResult createShareTake(@RequestBody ActivityInfoVo activityInfoVo)
    {
        ActivityInfo activityInfo= activityInfoService.getOne(new QueryWrapper<ActivityInfo>().eq("status","2").eq("activity_code",activityInfoVo.getActivityCode()));
        if(activityInfo==null){
            return AjaxResult.error("活动不存在或未开启");
        }
        activityInfo.setNum(activityInfo.getNum()+1);
        activityInfoService.updateById(activityInfo);
        return AjaxResult.success();
    }

    @ApiOperation(value ="用户获取微信授权信息")
    @PostMapping("/get/openid/user")
    public AjaxResult bindingActivityTakeInfoUser(@RequestBody OpenIdVo openIdVo)
    {
        WxOAuth2AccessToken wxOAuth2AccessToken= wxUserService.bindingActivityTakeInfo(openIdVo.getCode());
        if(null==wxOAuth2AccessToken){
            return AjaxResult.error("绑定失败",openIdVo);
        }
        return AjaxResult.success(wxOAuth2AccessToken);
    }

    @ApiOperation(value ="统计活动参与数量")
    @GetMapping("/statistics/num")
    public AjaxResult statisticsNum(ActivityInfoVo activityInfoVo)
    {
        ActivityInfo activityInfo= activityInfoService.getOne(new QueryWrapper<ActivityInfo>().ne("status","1").eq("activity_code",activityInfoVo.getActivityCode()));
        if(activityInfo!=null){
            Map<String,String> map=new HashMap<>();
            //活动访问量
            map.put("visit", String.valueOf(activityInfo.getNum()));
            //投票人数
            map.put("people", String.valueOf(iVoteInfoService.count()));
            //参赛作品
            map.put("share", String.valueOf(iShareInfoService.count(new QueryWrapper<ShareInfo>().eq("status","2"))));
            return AjaxResult.success(map);
        }
        return AjaxResult.error("活动不存在或未开启");
    }

    @ApiOperation(value ="查询年味分享列表")
    @GetMapping("/list/shareinfo")
    public TableDataInfo listShareinfo(ShareInfoVoList shareInfoVoList )
    {
        Integer pageIndex = 1;
        Integer pageSize = 10;
        if (null!=shareInfoVoList.getPageNum()){
            pageIndex=shareInfoVoList.getPageNum();
        }
        if (null!=shareInfoVoList.getPageSize()){
            pageSize=shareInfoVoList.getPageSize();
        }
        IPage<ShareInfo> page = new Page<>(pageIndex, pageSize);
        QueryWrapper<ShareInfo> queryWrapper= new QueryWrapper<ShareInfo>();
        if(StringUtils.isNotEmpty(shareInfoVoList.getShareCode())){
            queryWrapper.eq("id",shareInfoVoList.getShareCode());
        }
        queryWrapper.eq("status","2");
        queryWrapper.orderByDesc("num","id");
        IPage<ShareInfo> iPage=iShareInfoService.page(page,queryWrapper);
        List<ShareInfo> list =iPage.getRecords();
        list.stream().forEach(s->{
            s.setShareCode(s.getId());
        });
        return getDataTable(list);
    }

    @ApiOperation(value ="上传图片")
    @PostMapping("/share/image")
    public AjaxResult shareImage(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String share = FileUploadUtils.upload(JooLunConfig.getSharePath(), file);
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", share);
                return ajax;
            }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    @ApiOperation(value ="用户参与年味分享")
    @PostMapping("/create/shareinfo")
    public AjaxResult createShareTake(@RequestBody ShareInfoVo shareInfoVo)
    {
        iShareInfoService.insertShareInfoVo(shareInfoVo);
        return AjaxResult.success();
    }

    @ApiOperation(value ="获取年味详细")
    @GetMapping(value = "/shareinfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        ShareInfo shareInfo= iShareInfoService.selectShareInfoById(id);
        shareInfo.setShareCode(shareInfo.getId());
        return AjaxResult.success(shareInfo);
    }

    @ApiOperation(value ="支持用户年味分享")
    @PostMapping("/support/shareinfo")
    public AjaxResult supportShareTake(@RequestBody SupportShareInfoVo supportShareInfoVo)
    {
        ActivityInfo activityInfo= activityInfoService.getOne(new QueryWrapper<ActivityInfo>().eq("status","2").eq("activity_code","CU1M6"));
        if(activityInfo==null){
            return AjaxResult.error("活动已结束，不支持投票");
        }
        ShareInfo shareInfo= iShareInfoService.getOne(new QueryWrapper<ShareInfo>().eq("id",supportShareInfoVo.getShareCode()));
        if(shareInfo==null){
            return AjaxResult.error("年味分享不存在");
        }
        //判断用户是否已经推荐过
        Integer num= iVoteInfoService.count(new QueryWrapper<VoteInfo>()
                //.eq("share_code",supportShareInfoVo.getShareCode())
                .eq("open_id",supportShareInfoVo.getOpenId())
                .eq("type","1")
                .ge("create_time",DateUtils.getDate()+" 00:00:00")
                .le("create_time",DateUtils.getDate()+" 23:59:59")
        );
        if(num>=3){
            return AjaxResult.error("今日已经推荐过三次，明日继续");
        }
        shareInfo.setNum(shareInfo.getNum()+1);
        iShareInfoService.updateById(shareInfo);
        //新增支持
        VoteInfo voteInfo=new VoteInfo();
        voteInfo.setShareCode(supportShareInfoVo.getShareCode());
        voteInfo.setOpenId(supportShareInfoVo.getOpenId());
        voteInfo.setType("1");
        voteInfo.setCreateTime(DateUtils.getNowDate());
        iVoteInfoService.insertVoteInfo(voteInfo);
        return AjaxResult.success();
    }

    @ApiOperation(value ="分享用户年味分享")
    @PostMapping("/share/shareinfo")
    public AjaxResult shareShareTake(@RequestBody SupportShareInfoVo supportShareInfoVo)
    {
        ActivityInfo activityInfo= activityInfoService.getOne(new QueryWrapper<ActivityInfo>().eq("status","2").eq("activity_code","CU1M6"));
        if(activityInfo==null){
            return AjaxResult.error("活动已结束，不支持分享");
        }
        ShareInfo shareInfo= iShareInfoService.getOne(new QueryWrapper<ShareInfo>().eq("id",supportShareInfoVo.getShareCode()));
        if(shareInfo==null){
            return AjaxResult.error("年味分享不存在");
        }
        //判断用户是否已经分享过
        Integer num= iVoteInfoService.count(new QueryWrapper<VoteInfo>()
                //.eq("share_code",supportShareInfoVo.getShareCode())
                .eq("open_id",supportShareInfoVo.getOpenId())
                .eq("type","2")
                .ge("create_time",DateUtils.getDate()+" 00:00:00")
                .le("create_time",DateUtils.getDate()+" 23:59:59")
        );
        if(num>=1){
            return AjaxResult.error("今日已经分享过一次，明日继续");
        }
        shareInfo.setNum(shareInfo.getNum()+1);
        iShareInfoService.updateById(shareInfo);
        //新增支持
        VoteInfo voteInfo=new VoteInfo();
        voteInfo.setShareCode(supportShareInfoVo.getShareCode());
        voteInfo.setOpenId(supportShareInfoVo.getOpenId());
        voteInfo.setType("2");
        voteInfo.setCreateTime(DateUtils.getNowDate());
        iVoteInfoService.insertVoteInfo(voteInfo);
        return AjaxResult.success();
    }


    @ApiOperation(value ="微信分享使用")
    @PostMapping("/share/url")
    public AjaxResult shareUrl(@RequestBody ShareUrlVo shareUrlVo) throws Exception {
        WxJsapiSignature wxJsapiSignature = wxService.createJsapiSignature(shareUrlVo.getUrl());
        return AjaxResult.success(wxJsapiSignature);
    }
}
